﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using com.mservice.momo.msg;
using MoMoTransferVN_WP.utils;

namespace MoMoTransferVN_WP.page
{
    public partial class LoginPage : PhoneApplicationPage, App.IMoMoMessageCome
    {
        long mCurrentIndex = 0;
        public LoginPage()
        {
            InitializeComponent();
            (Application.Current as MoMoTransferVN_WP.App).setCkb((App.IMoMoMessageCome)this);

        }

        public void onMoMoMessageCome(int cmdType, long cmdIndex, byte[] cmdBody)
        {
            if (cmdType == (int)MsgType.LOGIN_REPLY && cmdIndex == mCurrentIndex)
            {
                LogInReply reply = LogInReply.CreateBuilder().MergeFrom(cmdBody).Build();
                if (reply != null && reply.Result)
                {
                    SettingUtils.saveSetting(Assets.KEY_USER_LOGIN, true);

                    //todo xu ly login
                    Dispatcher.BeginInvoke(() =>
                    {
                        this.NavigationService.Navigate(new Uri("/page/MainPage.xaml", UriKind.Relative));
                    });
                }
                else
                {
                    LogUtils.f("Login khong thanh cong with " + reply.Rcode);
                }
            }
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            string deviceModel = Microsoft.Phone.Info.DeviceStatus.DeviceHardwareVersion;
            mCurrentIndex = App.getNextMsgId();
            MomoMessage msg = MoMoReq.processLogIn(mCurrentIndex, txtPassword.Password, deviceModel);
            (Application.Current as MoMoTransferVN_WP.App).mMoMoTcpClient.sendMoMoMesage(msg);
        }


        public void onDisconnectWithError(string error)
        {
            throw new NotImplementedException();
        }
    }
}